package com.mayblackcat.dy.controller;

import com.mayblackcat.dy.FrontEndData.AjaxResult;
import com.mayblackcat.dy.config.RuoYiConfig;
import com.mayblackcat.dy.config.ServerConfig;
import com.mayblackcat.dy.constant.Constants;

import com.mayblackcat.dy.entity.User;
import com.mayblackcat.dy.service.LoginService;
import com.mayblackcat.dy.service.UpLoadService;
import com.mayblackcat.dy.service.UserService;
import com.mayblackcat.dy.service.impl.UpLoadServiceImpl;
import com.mayblackcat.dy.utils.StringUtils;
import com.mayblackcat.dy.utils.file.FileUploadUtils;
import com.mayblackcat.dy.utils.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

//@RestController和@Controller区别:
// 1.使用@Controller 注解，在对应的方法上，视图解析器可以解析return 的jsp,html页面，并且跳转到相应页面，若返回json等内容到页面，则需要加@ResponseBody注解
// 2.如果只是使用@RestController注解控制层方法，则控制层中的方法无法返回jsp页面，或者html，配置的视图解析器 InternalResourceViewResolver不起作用，返回的内容就是Return里的内容。
@RestController
@CrossOrigin
@RequestMapping("/login")
public class LoadUpController {

    private static final Logger log = LoggerFactory.getLogger(LoadUpController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private UpLoadService upLoadService;

    @Autowired
    private UserService userService;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 上传视频请求
     */
    @PostMapping(value = "/upload")
    @Scope("prototype")
    public AjaxResult uploadFile(@RequestParam("video") MultipartFile video, @RequestParam("videoTitle") String title, @RequestParam("videoDes")String des,@RequestParam("id")long id) throws Exception
    {




        return upLoadService.upLoad(video,title,des,id);
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
